import itsdangerous
from django import http
from django.core.files.storage import Storage
from django.db import models
from django.contrib.auth.backends import ModelBackend
import re


from django.contrib.auth.mixins import LoginRequiredMixin

from meiduo_mall.settings.dev import FDFS_BASE_URL
from .models import User

def judge(username):
    try:
        #在自带的验证里面 也是只验证一个username值，密码是单独验证
        if re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            #user = 手机号
            user = User.objects.get(mobile=username)
            print(user)
        else:
            user = User.objects.get(username=username)
    except Exception:
        #出错就是不存在
        return None
    else:
        #正常执行则返回user
        return user



#自定义用户认证
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = judge(username)

        #检验user是否存在 ,并且判断密码是否正确
        if user and user.check_password(password):
            return user


#自定义判断是否登陆返回非网页而是json的 LoginRequiredMixin
class LoginRequiredJsonMixin(LoginRequiredMixin):
    def handle_no_permission(self):
        #这个函数名没改写之前是返回报错的
        #改写返回json
        return http.JsonResponse({'code':'-2',"errmsg":"用户未登录"})

#加密解密
class jiajiemi(object):
    def jiemi(self,data):
        #有效期一天

        a = itsdangerous.TimedJSONWebSignatureSerializer(secret_key='5_p($zf+#m3xlxghs#_ln3b1axdklz)xtuk&td8wxpyc&x9t8l',expires_in=3600*24)
        return a.loads(data)


    def jiami(self,data):

        a = itsdangerous.TimedJSONWebSignatureSerializer(secret_key='5_p($zf+#m3xlxghs#_ln3b1axdklz)xtuk&td8wxpyc&x9t8l',expires_in=3600*24)
        return a.dumps(data).decode()


#定义模型类基类 ,加创建和更新时间字段,只继承而不会被迁移 因为有Meta absrtact

class BaseModel(models.Model):
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        abstract = True  # 说明是抽象模型类, 用于继承使用，数据库迁移时不会创建BaseModel的表





